import numpy as np
import matplotlib.pyplot as plt

X_train = np.array([
    [158, 64],
    [170, 86],
    [183, 84],
    [191, 80],
    [155, 49],
    [163, 59],
    [180, 67],
    [158, 54],
    [170, 65],

])
y_train = ['male', 'male', 'male', 'male', 'female', 'female', 'female', 'female', 'female']

plt.figure()
plt.title("Human Height and Weights by Sex")
plt.xlabel("Heigh in cm")
plt.ylabel("weigh in kg")

for i, x in enumerate(X_train):
    plt.scatter(x[0], x[1], c='k', marker='x' if y_train[i] == 'male' else 'D')

plt.grid(True)
plt.show()

x = np.array([[155, 70]])
distances = np.sqrt(np.sum((X_train - x) ** 2, axis=1))
nearest_indices_indices = distances.argsort()[:3]
nearest_indices_genders = np.take(y_train, nearest_indices_indices)

from collections import Counter

b = Counter(np.take(y_train, distances.argsort()[:3]))
# 预测结果
prSex = b.most_common(1)[0][0]

# KNN分类器
from sklearn.preprocessing import LabelBinarizer
from sklearn.neighbors import KNeighborsClassifier

# 文本转数字
lb = LabelBinarizer()
y_train_binarized = lb.fit_transform(y_train)

K = 3

clf = KNeighborsClassifier(n_neighbors=K)
clf.fit(X_train, y_train_binarized.reshape(-1))
prediction_binarized = clf.predict(np.array([155, 70]).reshape(1, -1))[0]
prediction_label = lb.inverse_transform(prediction_binarized)
print(prediction_label)

# 测试
X_test = np.array([[168, 65], [180, 96], [160, 52], [169, 67]])
y_test = ['male', 'male', 'female', 'female']
y_test_binarized = lb.transform(y_test)

predictions_binarized = clf.predict(X_test)
prediction_labels = lb.inverse_transform(predictions_binarized)

print(prediction_labels)

# 预测的准确性

from sklearn.metrics import accuracy_score

Accuracy = accuracy_score(y_test_binarized, predictions_binarized)
print('Accuracy:', Accuracy)

# 精准率
from sklearn.metrics import precision_score

Precision_score = precision_score(y_test_binarized, predictions_binarized)
print('Precision_score:', Precision_score)

# 召回率
from sklearn.metrics import recall_score
Recall_score = recall_score(y_test_binarized, predictions_binarized)
print('recall_score:', Recall_score)

#F1得分 是精准率和召回率的调和平均值
from sklearn.metrics import f1_score
F1_score = f1_score(y_test_binarized, predictions_binarized)
print('F1_score:', F1_score)

#马修斯相关系数 是另一种对分类器性能的进行衡量的选择
from sklearn.metrics import matthews_corrcoef
Matthews_corrcoef = matthews_corrcoef(y_test_binarized, predictions_binarized)
print('Matthews_corrcoef:', Matthews_corrcoef)

from sklearn.metrics import classification_report
Classification_report = classification_report(y_test_binarized, predictions_binarized)
print('Classification_report:', Classification_report)

